#include "ProductPanel.h"


ProductPanel::ProductPanel()
{
    buttonLayout = new QHBoxLayout();
    widgetLayout = new QVBoxLayout();
    addButton = new QPushButton("添加商品");
    queryButton = new QPushButton("商品查询");
    sortButton = new QPushButton("商品排序");
    adminButton = new QPushButton("管理员面板");
    removeButton = new QPushButton("删除商品");
    productTable = new QTableWidget();

    buttonLayout->addWidget(addButton);
    buttonLayout->addWidget(removeButton);
    buttonLayout->addWidget(queryButton);
    buttonLayout->addWidget(sortButton);
    buttonLayout->addWidget(adminButton);
    widgetLayout->addLayout(buttonLayout);
    widgetLayout->addWidget(productTable);

    setWindowTitle("商品管理");
    setLayout(widgetLayout);


    removeButton->setDisabled(true);
    QStringList list;
    list << "商品名称" << "进价(元)" << "售价(元)" << "利润(元)" << "毛利率(%)" << "库存" << "单位";
    productTable->setColumnCount(list.size());
    productTable->setHorizontalHeaderLabels(list);
    productTable->setSelectionMode(QAbstractItemView::MultiSelection);
    for (const auto &product: *getProductList()) addProductToTable(product);
    productTable->setEditTriggers(QAbstractItemView::NoEditTriggers);

    connect(addButton, SIGNAL(clicked()), this, SLOT(addButtonClickedSlot()));
    connect(productTable, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(productTableDoubleClickedSlot(int, int)));
    connect(productTable, SIGNAL(itemSelectionChanged()), this, SLOT(tableSelectRowSlot()));
    connect(removeButton, SIGNAL(clicked()), this, SLOT(removeButtonClickedSlot()));
    connect(queryButton, SIGNAL(clicked()), this, SLOT(queryButtonClickedSlot()));
    connect(sortButton, SIGNAL(clicked()), this, SLOT(sortButtonClickedSlot()));
    connect(adminButton, SIGNAL(clicked()), this, SLOT(adminButtonClickedSlot()));
}

void ProductPanel::loginSlot(bool isAdmin)
{
    this->show();
    this->adminButton->setDisabled(not isAdmin);
}

void ProductPanel::closeEvent(QCloseEvent *event)
{
    saveUserList();
    saveProductList();
}

void ProductPanel::addProductToTable(Product product)
{
    QTableWidgetItem *item1 = new QTableWidgetItem(),
            *item2 = new QTableWidgetItem(),
            *item3 = new QTableWidgetItem(),
            *item4 = new QTableWidgetItem(),
            *item5 = new QTableWidgetItem();

    item1->setData(Qt::DisplayRole, QVariant(product.purchasePrice));
    item2->setData(Qt::DisplayRole, QVariant(product.sellingPrice));
    item3->setData(Qt::DisplayRole, QVariant(product.getProfit()));
    item4->setData(Qt::DisplayRole, QVariant(product.getGrossProfitMargin()));
    item5->setData(Qt::DisplayRole, QVariant(product.stock));

    int r = productTable->rowCount();
    productTable->setRowCount(r + 1);

    productTable->setItem(r, 0, new QTableWidgetItem(product.name));
    productTable->setItem(r, 1, item1);
    productTable->setItem(r, 2, item2);
    productTable->setItem(r, 3, item3);
    productTable->setItem(r, 4, item4);
    productTable->setItem(r, 5, item5);
    productTable->setItem(r, 6, new QTableWidgetItem(product.unit));
}

void ProductPanel::modifyProductFromTable(Product product, int r)
{
    QTableWidgetItem *item1 = new QTableWidgetItem(),
            *item2 = new QTableWidgetItem(),
            *item3 = new QTableWidgetItem(),
            *item4 = new QTableWidgetItem(),
            *item5 = new QTableWidgetItem();

    item1->setData(Qt::DisplayRole, QVariant(product.purchasePrice));
    item2->setData(Qt::DisplayRole, QVariant(product.sellingPrice));
    item3->setData(Qt::DisplayRole, QVariant(product.getProfit()));
    item4->setData(Qt::DisplayRole, QVariant(product.getGrossProfitMargin()));
    item5->setData(Qt::DisplayRole, QVariant(product.stock));

    productTable->setItem(r, 0, new QTableWidgetItem(product.name));
    productTable->setItem(r, 1, item1);
    productTable->setItem(r, 2, item2);
    productTable->setItem(r, 3, item3);
    productTable->setItem(r, 4, item4);
    productTable->setItem(r, 5, item5);
    productTable->setItem(r, 6, new QTableWidgetItem(product.unit));
}

void ProductPanel::addButtonClickedSlot()
{
    auto *dialog = new AddProductDialog();
    if (dialog->exec() == QDialog::DialogCode::Accepted)
    {
        addProductToTable(*dialog->product);
        getProductList()->append(*dialog->product);
    }
}

void ProductPanel::productTableDoubleClickedSlot(int row, int column)
{
    Product *product = queryProductByName(productTable->item(row, 0)->text());
    bool ok = false;
    if (column == 0)
    {
        QString temp = QInputDialog::getText(this, "修改商品名称", "新的商品名称",
                                             QLineEdit::Normal, QString(), &ok);
        if (ok) product->name = temp;
    } else if (column == 1)
    {
        double temp = QInputDialog::getDouble(this, "修改进价", "新的进价(元)",
                                              0, -2147483647, 2147483647, 1, &ok);
        if (ok) product->purchasePrice = temp;
    } else if (column == 2)
    {
        double temp = QInputDialog::getDouble(this, "修改售价", "新的售价(元)",
                                              0, -2147483647, 2147483647, 1, &ok);
        if (ok) product->sellingPrice = temp;
    } else if (column == 5)
    {
        int temp = QInputDialog::getInt(this, "修改库存", "新的库存",
                                        0, -2147483647, 2147483647, 1, &ok);
        if (ok) product->stock = temp;
    } else if (column == 6)
    {
        QString temp = QInputDialog::getText(this, "修改单位", "新的单位",
                                             QLineEdit::Normal, QString(), &ok);
        if (ok) product->unit = temp;
    } else if (!ok)
    {
        return;
    }
    modifyProductFromTable(*product, row);
}

void ProductPanel::tableSelectRowSlot()
{
    if (productTable->selectedRanges().size() == 1
        && productTable->selectedRanges()[0].rowCount() == 1
        && productTable->selectedRanges()[0].columnCount() == productTable->columnCount())
    {
        removeButton->setDisabled(false);
        selectedRow = productTable->selectedRanges()[0].topRow();
    } else
        removeButton->setDisabled(true);
}

Product ProductPanel::getProductFromTable(int row) const
{
    return Product(
            productTable->item(row, 0)->text(),
            productTable->item(row, 1)->text().toDouble(),
            productTable->item(row, 2)->text().toDouble(),
            productTable->item(row, 3)->text().toUShort(),
            productTable->item(row, 4)->text()
    );
}

void ProductPanel::removeButtonClickedSlot()
{
    auto btn = QMessageBox::question(this, "删除商品",
                                     QString("是否删除商品“%1?“").arg(productTable->item(selectedRow, 0)->text()));
    if (btn == QMessageBox::Yes)
    {
        getProductList()->removeOne(getProductFromTable(selectedRow));
        productTable->removeRow(selectedRow);
    };
}

void ProductPanel::queryButtonClickedSlot()
{
    if (queryButton->text() == "商品查询")
    {
        QStringList list;
        bool ok;
        list << "商品名称" << "售价" << "进价" << "单位";
        QString item = QInputDialog::getItem(this, "商品查询", "选择查询关键字",
                                             list, 0, false, &ok);
        if (!ok) return;
        if (item == list[0])
        {
            QString value = QInputDialog::getText(this, "商品名称", "商品名称");
            for (int i = 0; i < productTable->rowCount(); ++i)
                if (getProductFromTable(i).name != value)
                    productTable->hideRow(i);
        } else if (item == list[1])
        {
            double value = QInputDialog::getDouble(this, "售价", "售价");
            for (int i = 0; i < productTable->rowCount(); ++i)
                if (getProductFromTable(i).sellingPrice != value)
                    productTable->hideRow(i);
        } else if (item == list[2])
        {
            double value = QInputDialog::getDouble(this, "进价", "进价");
            for (int i = 0; i < productTable->rowCount(); ++i)
                if (getProductFromTable(i).purchasePrice != value)
                    productTable->hideRow(i);
        } else if (item == list[3])
        {
            QString value = QInputDialog::getText(this, "单位", "单位");
            for (int i = 0; i < productTable->rowCount(); ++i)
                if (getProductFromTable(i).unit != value)
                    productTable->hideRow(i);
        }
        queryButton->setText("停止查询");
    } else
    {
        for (int i = 0; i < productTable->rowCount(); ++i)
            productTable->showRow(i);
        queryButton->setText("商品查询");
    }
}

void ProductPanel::sortButtonClickedSlot()
{
    QStringList list;
    bool ok;

    list << "商品名称" << "进价" << "售价" << "利润" << "毛利率" << "库存" << "单位";
    int column = list.indexOf(QInputDialog::getItem(this, "商品排序", "选择排序关键字",
                                                    list, 0, false, &ok));
    if (!ok) return;

    list.clear();
    list << "降序" << "升序";
    QString type = QInputDialog::getItem(this, "商品排序", "选择排序方式",
                                         list, 0, false, &ok);
    if (!ok) return;

    if (type == list[0]) productTable->sortItems(column, Qt::DescendingOrder);
    else productTable->sortItems(column, Qt::AscendingOrder);
}

void ProductPanel::adminButtonClickedSlot()
{
    auto *dialog = new UserManageDialog();
    dialog->exec();
    getUserList()->clear();
    for (int i = 0; i < dialog->userTable->rowCount(); ++i)
        addUserToList(dialog->getUserFromTable(i));
}


